package com.tqz.zookeeper.rawapi.discovery;

import com.tqz.zookeeper.common.CuratorStandaloneBase;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.details.JsonInstanceSerializer;

import java.util.Collection;

/**
 * 实现服务发现的功能
 *
 * @author <a href="https://github.com/tian-qingzhao">tianqingzhao</a>
 * @since 2025/9/5 14:54
 */
@Slf4j
public class DiscoveryTest extends CuratorStandaloneBase {

    private static final String PATH = "/discovery/example";
    private static ServiceDiscovery<InstanceInfo> serviceDiscovery;

    public static void main(String[] args) throws Exception {
        testRegister();
    }

    public static void testRegister() throws Exception {
        CuratorFramework curatorFramework = getCuratorFramework();
        JsonInstanceSerializer<InstanceInfo> serializer = new JsonInstanceSerializer<InstanceInfo>(InstanceInfo.class);

        serviceDiscovery = ServiceDiscoveryBuilder
                .builder(InstanceInfo.class)
                .client(curatorFramework)
                .basePath(PATH)
                .serializer(serializer)
                .build();

        ServiceInstance<InstanceInfo> build =
                ServiceInstance.<InstanceInfo>builder()
                        .name("server-name-random")
                        .payload(InstanceInfo.builder().key1("key1").key2("key2").build())
                        .build();
        serviceDiscovery.registerService(build);
        printInstance();
    }

    public static void printInstance() throws Exception {

        Collection<ServiceInstance<InstanceInfo>> serviceInstances =
                serviceDiscovery.queryForInstances("server-name-random");
        serviceInstances.forEach(item -> {
            log.info("查询到的 Instance: {}", item);
        });
    }

}
